import axios from 'axios';

// 创建 axios 实例
const apiClient = axios.create({
  timeout: 10000, // 设置超时时间为10秒
  headers: {
    'Content-Type': 'application/json'
  }
});

// 重试配置
const RETRY_COUNT = 3;
const RETRY_DELAY = 1000; // 重试间隔（毫秒）

// 模拟数据（当API调用失败时使用）
const mockData = [
  {
    clientId: '服务器-01',
    systemStatus: {
      cpuUsage: 35,
      memoryUsage: 62,
      disks: [
        {
          path: '/',
          usagePercent: 45,
          freeSpace: 110,
          totalSpace: 200
        },
        {
          path: '/data',
          usagePercent: 78,
          freeSpace: 44,
          totalSpace: 200
        }
      ]
    },
    services: [
      { serviceName: 'Web服务', healthy: true },
      { serviceName: '数据库', healthy: true },
      { serviceName: '缓存服务', healthy: true }
    ]
  },
  {
    clientId: '服务器-02',
    systemStatus: {
      cpuUsage: 88,
      memoryUsage: 72,
      disks: [
        {
          path: '/',
          usagePercent: 89,
          freeSpace: 22,
          totalSpace: 200
        }
      ]
    },
    services: [
      { serviceName: 'Web服务', healthy: true },
      { serviceName: '数据库', healthy: false },
      { serviceName: '缓存服务', healthy: true }
    ]
  },
  {
    clientId: '服务器-03',
    systemStatus: {
      cpuUsage: 12,
      memoryUsage: 25,
      disks: [
        {
          path: '/',
          usagePercent: 15,
          freeSpace: 170,
          totalSpace: 200
        },
        {
          path: '/backup',
          usagePercent: 45,
          freeSpace: 110,
          totalSpace: 200
        }
      ]
    },
    services: [
      { serviceName: 'Web服务', healthy: true },
      { serviceName: '备份服务', healthy: true }
    ]
  }
];

/**
 * 带重试机制的API调用
 * @param {Function} apiCall - API调用函数
 * @param {number} retryCount - 重试次数
 * @returns {Promise} - 返回Promise
 */
async function callWithRetry(apiCall, retryCount = RETRY_COUNT) {
  try {
    return await apiCall();
  } catch (error) {
    if (retryCount > 0) {
      console.warn(`API调用失败，${retryCount}秒后重试...`, error.message);
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
      return callWithRetry(apiCall, retryCount - 1);
    } else {
      console.error('API调用达到最大重试次数，返回模拟数据', error);
      // 达到最大重试次数，返回模拟数据
      return mockData;
    }
  }
}

/**
 * 获取设备状态列表
 * @returns {Promise<Array>} - 返回设备状态列表
 */
export async function getMockStatusList() {
  try {
    // 使用重试机制调用API
    const res = await callWithRetry(() => 
      apiClient.get('http://58.213.66.34:3068/api/get-status-list')
    );
    
    // 如果返回的数据是模拟数据（非API响应）
    if (!res.data) {
      return res;
    }
    
    // 处理API返回的数据
    const processedData = res.data.map(item => ({
      clientId: item.clientId || '未知设备',
      systemStatus: {
        cpuUsage: item.cpuUsage || 0,
        memoryUsage: item.memoryUsage || 0,
        disks: (item.disks || []).map(d => ({
          path: d.path || '',
          usagePercent: d.usagePercent || 0,
          freeSpace: d.freeSpace || 0,
          totalSpace: d.totalSpace || 0
        }))
      },
      services: Array.isArray(item.services) ? item.services : []
    }));
    
    // 数据验证，确保至少有一个设备
    return processedData.length > 0 ? processedData : mockData;
  } catch (err) {
    console.error('获取状态列表失败，返回模拟数据', err);
    // 任何未捕获的错误，都返回模拟数据
    return mockData;
  }
}
